//
//  JoinUnenrollConnection.m
//  BVCMS
//
//  Created by Allen Thomas on 11/29/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "JoinUnenrollConnection.h"
#import "MeetingMemberRecord.h"
#import "BVCMSAppDelegate.h"

@implementation JoinUnenrollConnection

@synthesize meetingMemberRecord;

@synthesize indexPathInTableView;

@synthesize delegate;

@synthesize activeDownload;

@synthesize connection;

@synthesize orgId;

#pragma mark

- (void)dealloc {
    [meetingMemberRecord release];
    [indexPathInTableView release];
    [activeDownload release];
    [connection cancel];
    [connection release];
	[orgId release];
    [super dealloc];	
}

- (void)startDownload {
	BVCMSAppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
	
    self.activeDownload = [NSMutableData data];
	NSString *memberChange = @"True";
	if( [meetingMemberRecord.member isEqualToString:@"True"] ) {
		memberChange = @"False";
	}
	
	NSString *urlString = [NSString stringWithFormat:@"https://%@/iphone/JoinUnJoinOrg?PeopleId=%@&OrgId=%@&Member=%@", 
						   appdelegate.cmsServer,
						   meetingMemberRecord.peopleId,
						   orgId,
						   memberChange];
	NSLog(@"%@",urlString);
	
	NSMutableURLRequest *myRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString] ];
	[myRequest setTimeoutInterval:20.0];
	[myRequest addValue:appdelegate.username forHTTPHeaderField:@"username"];
	[myRequest addValue:appdelegate.password forHTTPHeaderField:@"password"];
	[myRequest setHTTPMethod:@"POST"];
	
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self];
	[myRequest release];
	
    self.connection = conn;
	
    [conn release];
	
}

- (void)cancelDownload {
    [self.connection cancel];	
    self.connection = nil;	
    self.activeDownload = nil;	
}

#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.activeDownload appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Clear the activeDownload property to allow later attempts	
    self.activeDownload = nil;
	
    // Release the connection now that it's finished
    self.connection = nil;
	
	[delegate joinUnenrollFailed:self.indexPathInTableView];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	NSString *output = [[NSString alloc] initWithData:activeDownload encoding:NSASCIIStringEncoding];
	NSLog(@"%@", output);
	[output release];
	
    self.activeDownload = nil;
	
    // Release the connection now that it's finished
    self.connection = nil;
	
    // call our delegate and tell it that our icon is ready for display
    [delegate joinUnenrollCallback:self.indexPathInTableView];
}


@end
